package com.wxxymaker.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author: Soft
 * @Date: 2018/6/29 22:54
 * @Desc: 文件处理工具
 */
public class FileUtils {
    private static final Logger log      = LoggerFactory.getLogger(FileUtils.class);
    private static       String basePath = Const.CLASSPATH.substring(0,
            Const.CLASSPATH.lastIndexOf("/"));

    /**
     * 清理临时文件夹
     */
    public static void clearTemp() {
        String readPath = basePath + "/upload/temp/";
        File file = new File(readPath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File df : files) {
                    df.delete();
                }
            }
        }
    }


    /**
     * 将文件保存在临时目录
     */
    public static String saveToTemp(byte[] input, String filename) {
        return save(input, "temp", filename);
    }

    /**
     * 将文件保存在指定目录
     * @param input 文件字节数组
     * @param type  类型文件夹
     * @param filename 文件名
     * @return web路径
     */
    public static String saveToUpload(byte[] input, String type, String filename) {
        return save(input, type, filename);
    }

    /**
     * 根据web路径删除文件
     * @param webPath web路径
     */
    public static boolean deleteByWebPath(String webPath) {
        String realPath = basePath + webPath;
        try {
            new File(realPath).delete();
            return true;
        } catch (Exception e) {
            log.error("文件删除失败！WebPath：{} Message：{}", webPath, e.getMessage());
        }
        return false;
    }

    /**
     * 将临时文件移动到上传文件下
     * @param type     文件所属文章类型
     * @param filename 文件名
     * @return web路径
     */
    public static String tempMvToUpload(String type, String filename) {
        String webPath  = "/upload/" + type + "/" + filename;
        String tempFile = basePath + "/upload/temp/" + filename;
        File   target   = new File(basePath + webPath);
        if (createFile(target)) {
            try {
                moveFile(new File(tempFile), target);
            } catch (Exception e) {
                log.error("文件移动失败！TempFile：{} Message：{}", tempFile, e.getMessage());
            }
        }
        return webPath;
    }

    /**
     * 将文件保存在指定目录下
     * @param input    文件输入流
     * @param filename 目标文件名
     * @return 文件web路径
     */
    private static String save(byte[] input, String dir, String filename) {
        String webPath  = "/upload/" + dir + "/" + filename;
        String readPath = basePath + webPath;
        File file = new File(readPath);
        FileOutputStream   out    = null;
        OutputStreamWriter writer = null;
        if (createFile(file)) {
            try {
                out = new FileOutputStream(file);
                if (filename.endsWith(".html")) {
                    writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                    writer.write(new String(input));
                    writer.flush();
                } else {
                    out.write(input);
                    out.flush();
                }
            } catch (Exception e) {
                log.error("文件保存失败！TargetFile：{} Message：{}", readPath, e.getMessage());
            } finally {
                try {
                    if (out != null) out.close();
                    if (writer != null) writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return webPath;
    }

    private static boolean createFile(File file) {
        if (!file.exists()) {
            file.getParentFile().mkdirs(); // 创建上级目录
            try {
                return file.createNewFile();
            } catch (Exception e) {
                log.error("文件创建失败！FilePath: {}", file.getAbsolutePath());
            }
        }
        return false;
    }

    private static void moveFile(File source, File target) {
        FileInputStream  in  = null;
        FileOutputStream out = null;
        try {
            in  = new FileInputStream(source);
            out = new FileOutputStream(target);

            byte[] bs = new byte[8192];
            int len = 0;
            while ((len = in.read(bs)) != -1) {
                out.write(bs, 0, len);
            }

            out.flush();
        } catch (Exception e) {
            log.error("ERROR: moveFile--> {}", e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                    source.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
